const validate = require('../middleware/validate');
const {body} = require("express-validator");
const {User} = require("../model/index");
const md5 = require('../util/md5')
const {Promise} = require("mongoose");

exports.register = validate([
    body('user.username').notEmpty().withMessage(`用户名不能为空`)
        .isLength({min: 5, max: 12}).withMessage(`用户名必须为大于5位小于12位`)
        .custom(async (value)=>{
            await User.findOne({username: value})
                .then(()=>{
                    return Promise.rejects();
                })
        }).withMessage(`用户已存在`)
        .bail(),
    body('user.password').notEmpty().withMessage(`密码不能为空`)
        .isLength({min: 5, max: 12}).withMessage(`密码必须位大于5位小于12位`)
        .bail(),
    body('user.email')
        .isEmail().withMessage(`邮箱格式不正确`)
        .notEmpty().withMessage(`邮箱不能为空`)
        .custom(async (value) => {
            await User.findOne({email: value})
                .then(value => {
                    if (value) {
                        return Promise.reject(`邮箱已经存在`);
                    }
                })
        })
        .bail()
])

exports.login = [
    validate([
        body('user.username').bail()
            .notEmpty().withMessage(`请输入用户名`),
        body('user.password').bail()
            .notEmpty().withMessage(`请输入密码！！`)
    ]),
    validate([
        body('user.username').bail()
            .custom(async (username,{req})=>{
                const user = await User.findOne({username:username})
                    .catch(err =>{
                        return Promise.reject()
                    });
                req.user = user;
            })
            .withMessage(`用户不存在或密码错误`),
    ]),
    validate([
        body('user.password').bail()
            .custom(async (password,{req})=>{
                if(md5(password)!=req.user.password){
                    return Promise.reject()
                }
            }).withMessage(`用户不存在或密码错误`)
    ])
]

